<template>
    <div>
        <a-select
            class="mr-r-m"
            v-model:value="current"
            style="width: 120px"
            :options="boards"
            :fieldNames="{'label':'name','value':'id'}"
            @change="onBoardChange"
         ></a-select>

      <a-select
          class="mr-r-m"
          v-model:value="range"
          style="width: 120px"
          :options="rangeOption"
      ></a-select>



      <a-radio-group v-model:value="valueType" button-style="solid" @change="onTypeChange">
        <a-radio-button value="inflow">净流入</a-radio-button>
        <a-radio-button value="amp">涨跌幅</a-radio-button>
      </a-radio-group>


      <a-select
        class="mr-l-m"
        style="width: 240px"
        v-model:value="focus"
        mode="multiple"
        :options="units"
        :fieldNames="{'label':'name','value':'code'}"
        @change="handleChangeFocus"
        :max-tag-count="2"
        :max-tag-placeholder="3"
        show-search
        allow-clear
      ></a-select>

        <a-button type="link" @click="syncBoard">
          <DownloadOutlined />更新数据
        </a-button>


        <a-button type="link" @click="open = true;">
          <PlusOutlined/>编辑成分
        </a-button>


      <!-- <a-button type="link" @click="showToday">
        查看今日
      </a-button> -->

        <div id="main"></div>

        <a-drawer
            v-model:open="open"
            title="成分列表">

                <a-list :data-source="units">
                    <template #renderItem="{ item }">
                        <a-list-item>
                            <template #extra>
                                <div class="extra">
                                    <a-button type="link" danger @click="removeUnit(item)">
                                        <template #icon>
                                            <CloseOutlined />
                                        </template>
                                    </a-button>
                                </div>
                            </template>
                            <a @click="showDetail(item)">{{ item.name }}</a>
                        </a-list-item>
                    </template>

                    <template #footer>
                        <div style="text-align: center;">
                            <a-button type="dashed" block @click="addStock">+新增</a-button>
                        </div>
                    </template>
                </a-list>

        </a-drawer>
        <stock-dialog :board-id="current" ref="stockDialog" @success="getUnits"/>

        <add-board-dialog ref="addBoardDialog" @success="refresh"/>

        <a-float-button @click="addBoard()" type="primary">
          <template #icon>
            <PlusOutlined/>
          </template>
        </a-float-button>
    </div>
</template>

<script>

import stock from './stock.vue';
import { Drawer,Select,FloatButton,List,ListItem,Modal,RadioGroup,RadioButton } from 'ant-design-vue';
import {PlusOutlined,CloseOutlined,DownloadOutlined} from "@ant-design/icons-vue";
import addBoardDialog from "./add.vue";
import {findBoard,findBoardById,removeUnit,syncBoard,syncBoardToday} from "@/api/board";
import {convertToChineseUnit} from "@/common/utils";

const currentKey = "BOARDBOARD";

function sortByInflowSum(data) {
    const inflowSums = {};
    data.forEach(item => {
        let sum = 0;
        item.klines.forEach(kline => {
            sum += parseFloat(kline.inflow) || 0;
        });
        inflowSums[item.name] = sum;
    });

    return [...data].sort((a, b) => {
        const sumA = inflowSums[a.name];
        const sumB = inflowSums[b.name];
        if (sumA !== sumB) {
            return sumB - sumA; // 总和降序
        }
        return a.name.localeCompare(b.name); // 名称升序
    });
}

function findMinMax(data,type) {
    let maxInflow = -Infinity;
    let minInflow = Infinity;
    let maxEntry = null;
    let minEntry = null;

    data.forEach(item => {
        item.klines.forEach(kline => {
            const inflow = parseFloat(kline[type]);
            if (inflow > maxInflow) {
                maxInflow = inflow;
                maxEntry = { ...kline, name: item.name };
            }
            if (inflow < minInflow) {
                minInflow = inflow;
                minEntry = { ...kline, name: item.name };
            }
        });
    });

    return {
        max: { value: maxInflow, ...maxEntry },
        min: { value: minInflow, ...minEntry }
    };
}


export default{
    components: {
        ADrawer: Drawer,
        stockDialog:stock,
        PlusOutlined,
        CloseOutlined,
        DownloadOutlined,
        addBoardDialog,
        ASelect:Select,
        AFloatButton: FloatButton,
        AList: List,
        AListItem: ListItem,
        ARadioGroup:RadioGroup,
        ARadioButton: RadioButton
    },
    data(){
        return {
            //inflow：净流入,amp:涨跌幅
            valueType: 'inflow',
            myChart: null,
            current: null,
            range:null,
            open: false,
            focus:[],
            boards: [],
            units: [],
            rangeOption:[
              {
                value: 7,
                label: '最近7天',
              },
              {
                value: 14,
                label: '最近14天',
              },
              {
                value: 30,
                label: '最近30天',
              },
              {
                value: 90,
                label: '最近90天',
              }
            ]
        }
    },
    mounted(){
        this.refresh();


        var chartDom = document.getElementById('main');

        var myChart = echarts.init(chartDom,
            null,
            {renderer: "canvas"});


        this.myChart = myChart;

    },
    methods: {
      handleChangeFocus(){
        this.updateChart();
      },
      onTypeChange(){
      
        this.updateChart()
      },
      showToday(){
        syncBoardToday("603259.SH").then(res=>{

          console.log((res.data['f138'] + res.data['f141'] + res.data['f144'] + res.data['f147']) ,
           (res.data['f139'] + res.data['f142'] + res.data['f145'] + res.data['f148']))

        })
      },
        updateChart(data=this.units){

          if (this.focus.length!==0){
            data = this.units.filter(item => this.focus.includes(item.code))
          }

        
          let _data = [];

          let days = [];

          data.forEach(a=>{

            let temp = [];

            if (a.klines){

              a.klines.forEach(b=>{

                let single = {}

                let arr = b.split(",");

                if (!days.includes(arr[0])){
                  days.push(arr[0])
                }

                single.date = arr[0];
                single.inflow = arr[1];
                single.price = arr[2];
                single.amp = arr[3];

                temp.push(single)

              })

            }

            _data.push({
              klines: temp,
              name: a.name,
              code: a.code
            })
          })

          _data = sortByInflowSum(_data);


          let stocks = [];
          let chartData = [];

          days.sort((a, b) => new Date(a) - new Date(b));


          _data.forEach((a,ai)=>{
            stocks.push(a.name);

            a.klines.forEach((b)=>{

              let di = days.findIndex(c=> c === b.date);

              chartData.push([di,ai,Number(b[this.valueType])])

            })

          })

          let {min,max} = findMinMax(_data,this.valueType);

          var absMax = Math.max(Math.abs(min.value), Math.abs(max.value));

          let option = {
            tooltip: {
              position: 'top'
            },
            grid: {
              height: '100%',
              top: '120px',
              bottom: '20px'
            },
            xAxis: {
              type: 'category',
              data: days,
              splitArea: {
                show: true
              }
            },
            yAxis: {
              type: 'category',
              data: stocks,
              splitArea: {
                show: true
              }
            },
            visualMap: {
              show: false,
              calculable: false,
              hoverLink: false,
              min: -absMax,
              max: absMax,
              orient: 'vertical',
              left: '0',
              top: '0',
              inRange: {
                  color: ['#008000','#ffffff','#ff0000']
              }
            },
            series: [
              {
                name: 'cartesian',
                type: 'heatmap',
                data: chartData,
                label: {
                  show: false
                },
                symbolSize: function (data) {
                    return Math.log(Math.abs(data[2]) + 1) / 3 + 5;
                },
                tooltip: {
                  show: true,
                  formatter(params){

                    let klines = _data[params.data[1]].klines;

                    let {amp,inflow,price,date} = klines.find(a=>a.date === days[params.data[0]]);


                    let ampColor = 'red';

                    let color = 'green'

                    if (inflow > 0){
                      color = 'red'
                    }

                    if (amp.includes("-")){
                      ampColor = 'green';
                    }

                    return `<b>${stocks[params.data[1]]}</b> <br/> <span>${date}</span>
                    <p style="color:${color}">净流入:${convertToChineseUnit(inflow)}</p>
                    <p style="color:${ampColor}">当天价格: ${price}</p>
                    <p style="color:${ampColor}">涨跌幅:${amp}%</p>`
                  }
                }
              }
            ],
          };


          this.$nextTick(()=>{
              this.myChart.resize({
                  height: stocks.length * 34 + 200
              })


              this.myChart.setOption(option);
          })
        },
        addStock(){
            this.$refs['stockDialog'].open();
        },
        addBoard(){
            this.$refs['addBoardDialog'].open();
        },
        showDetail(item){
          this.$refs['stockDialog'].open(item);
        },
        syncBoard(){
          

          if (!this.current || !this.range){
              Modal.info({
                title: '失败',
                content: "当前看板无法更新",
              });
            return;
          }

          syncBoard({
            id:this.current,
            range:this.range,
          }).then(res=>{
            if(res.msg!==""){
              Modal.info({
                title: '有失败数据',
                content: res.msg,
              });
            } else {
              this.focus = [];
              this.units = res.data.units;
              this.range = res.data.range;

              this.updateChart(res.data.units);
            }
          })
        },
        refresh(){

            let current = localStorage.getItem(currentKey);

            if (current){
                this.current = current;
            }

            findBoard().then(res=>{
                this.boards = res.data.rows;

                if (!current){
                  this.current = res.data.rows[0]._id;
                }

                this.getUnits();
            })
        },
        getUnits(){
          findBoardById(this.current).then(res=>{
            this.units = res.data.units;
            console.log(this.units)
            this.range = res.data.range;

            this.updateChart(res.data.units);
          })
        },
        onBoardChange(){
            this.focus = [];
            localStorage.setItem(currentKey,this.current);
            this.getUnits();
        },
        removeUnit(item){
          Modal.confirm({
            title: "确认删除",
            content: "真的要删除"+item.name+"吗?",
            onOk:()=>{
                removeUnit(item._id).then(res=>{
                  this.getUnits();
                })
            }
          })
        }
    }

}

</script>
